package com.gitee.magic.framework.head.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import com.gitee.magic.core.converter.AbstractConverterEditor;
import com.gitee.magic.core.converter.DocDescription;
import com.gitee.magic.core.exception.ApplicationException;
import com.gitee.magic.framework.head.utils.TimeUtils;

/**
 * @author start
 */
@DocDescription(TimeUtils.YYYYMMDDHHMMSS)
public class DateTimeConverterEditor extends AbstractConverterEditor<String> {

	public DateTimeConverterEditor(Class<?> prototype) {
		super(prototype);
	}

	@Override
	public void restore(Object value) {
		if (value != null) {
			setValue(DateTimeConverterEditor.restoreValue(value,TimeUtils.YYYYMMDDHHMMSS));
		}
	}

	@Override
	public String converter() {
		if (getValue() == null) {
			return null;
		}
		SimpleDateFormat sd = new SimpleDateFormat(TimeUtils.YYYYMMDDHHMMSS);
		return sd.format(getValue());
	}
	
	@Override
	public Object getSource() {
		return converter();
	}
	
	public static Object restoreValue(Object value,String format) {
		Class<?> type=value.getClass();
		if(type.equals(String.class)) {
			SimpleDateFormat sd = new SimpleDateFormat(format);
			try {
				return sd.parse(String.valueOf(value));
			} catch (ParseException e) {
				throw new ApplicationException(e);
			}
		}else {
			return com.gitee.magic.converter.DateConverterEditor.restoreDataValue(value);
		}
	}

}
